import React, { PureComponent, ReactNode, ReactElement } from 'react';
import ReactDOM from 'react-dom';
import BasicModal from '../BasicModal';
import './index.less';
interface IDOMOpts {
  wrapClassName?: string;
  title?: string;
  header?: string;
  phone?: string;
  warnInfo?: string | any;
  content?: string;
  errorCode?: number;
  okText?: ReactNode | ReactElement | string;
  oneclstag?: string;
  icon?: string;
  onOneBtnFunc?: () => void; // 一个按钮触发的回调函数
  cancelText?: string; // 取消文案
  cancelBtnFunc?: () => void; // 第二个按钮触发的回调函数
  isShowDDCS?: boolean; // 是否展示联系咚咚客服
  cancelRTBtn?: boolean | undefined; // 是否展示报错按钮
}

interface IDomModalProps extends IDOMOpts {
  onCancel?: () => void;
  isError?: boolean;
}

interface IDomModalState {
  isVisable: boolean;
  [name: string]: any;
}

export class DOMModal extends PureComponent<IDomModalProps, IDomModalState> {
  static setState: any;
  constructor(props: IDomModalProps) {
    super(props);
    this.state = {
      isVisable: true
    };
  }

  static selfWrapObj: {
    [name: string]: HTMLElement;
  } = {};

  static handleOpenModal(opts: IDOMOpts) {
    const selfWrapKeys = Object.keys(DOMModal.selfWrapObj);
    if (selfWrapKeys.length) return null;

    let randomNum = Array.from({ length: 8 }, () => {
      return ['a', 'b', 'c', 'd', 'e', 'f', 'g'][Math.floor(Math.random() * 6)];
    }).join(''); // 获取随机ID， 生成弹窗
    this.selfWrapObj[`selfWrap${randomNum}`] = document.createElement('div');

    if (!document.getElementById('root')) {
      document.body.appendChild(this.selfWrapObj[`selfWrap${randomNum}`]);
    } else {
      (document.getElementById('root') as any).appendChild(
        this.selfWrapObj[`selfWrap${randomNum}`]
      );
    }
    ReactDOM.render(
      <DOMModal
        onCancel={() => DOMModal.handleCloseModal(`selfWrap${randomNum}`)}
        warnInfo={opts.warnInfo}
        {...opts}
      />,
      this.selfWrapObj[`selfWrap${randomNum}`]
    );
  }

  /**
   *
   * @param modalName 传入需要干掉弹窗的标识
   */
  static handleCloseModal(modalName: string) {
    ReactDOM.unmountComponentAtNode(this.selfWrapObj[modalName]); // 清除子节点
    (document.getElementById('root') as any).removeChild(
      this.selfWrapObj[modalName]
    ); // 清除元素
    delete this.selfWrapObj[modalName];
  }

  // 清除所有的Modal ？解决弹窗无法移除问题
  static handleClearAllModal() {
    const modalList = document.querySelectorAll('.modal'); // 获取到所有的类名为modal的弹窗
    if (Object.keys(this.selfWrapObj).length) {
      for (let modalName in this.selfWrapObj) {
        delete this.selfWrapObj[modalName];
      }
    }
    modalList.length &&
      modalList.forEach(modal => {
        const parentParent = modal.parentElement;
        parentParent ? parentParent.removeChild(modal) : void 0;
      });
    return true;
  }

  render() {
    const { cancelText, cancelBtnFunc } = this.props;
    return (
      <BasicModal
        cancelRTBtn={this.props.cancelRTBtn}
        wrapClassName={this.props.wrapClassName || 'dom-modal'}
        oneclstag={this.props.oneclstag}
        onCancel={this.props.onCancel}
        errorCode={this.props.errorCode!}
        footer={
          <>
            {cancelBtnFunc && (
              <div
                className="btn modal-cancel-btn"
                style={{ marginRight: '.38rem' }}
                onClick={() => {
                  cancelBtnFunc && cancelBtnFunc();
                }}
              >
                {cancelText || '取消'}
              </div>
            )}
            <div
              {...{ clstag: this.props.oneclstag }}
              className="btn modal-confirm-btn "
              onClick={() => {
                this.props.onOneBtnFunc
                  ? this.props.onOneBtnFunc()
                  : this.props.onCancel!();
              }}
            >
              {this.props.okText || '我知道了'}
            </div>
          </>
        }
        visible={this.state.isVisable}
        children={
          <div className="dom-modal-container">
            <div className="dom-modal-container-title">{this.props.title}</div>
            {this.props.content ? (
              <div className="dom-modal-container-content">
                {this.props.content}
              </div>
            ) : null}
          </div>
        }
      />
    );
  }
}

export const handleClearAllModal = DOMModal.handleClearAllModal;
